/* File:        	DaemonSocketChannel.java
* Package:			org.esi.authz.comm
* Created:      	29-abr-2011
* Last Changed: 	0:08:09
* Author:       	Borja Urkizu borja.urquizu@tecnalia.com
*
*   
* History:
*  Revision 1.0.0.0  
* 
* Tecnalia Research and Innovation
*/
package com.tecnalia.comm.channel.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.logging.Logger;

import com.tecnalia.comm.channel.IDChannel;

// TODO: Auto-generated Javadoc
/**
 * The Class DaemonSocketChannel.
 */
public class DSocketChannelImpl implements IDSocketChannel {
   	
    /** The logger. */
    private Logger logger = Logger.getLogger(this.getClass().getName());
    
    /** The ss channel. */
	private ServerSocketChannel ssChannel; 
    
	/** The client. */
	private SocketChannel client;
	
	private String host = "localhost";
	
	private int port = 50000;
    
    /** The status. */
    private int status = 0;
    
    /** The channel. */
    private IDChannel channel;
    
    /**
	    * Instantiates a new daemon socket channel.
	    *
	    */
    public DSocketChannelImpl() {
}
      
    /**
	    * Instantiates a new daemon socket channel.
	    *
	    * @param host the host
	    * @param port the port
	    */
    public DSocketChannelImpl(String hostIn, int portIn) {

        host = hostIn;
        port = portIn;

   	}
   	
	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

    
    public void start(IDChannel idaemon){

    	try {
			ssChannel = ServerSocketChannel.open();
	        ssChannel.configureBlocking(true);
	        //int port = 40000;
	        ssChannel.socket().bind(new InetSocketAddress(host, port));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	    
        
	    logger.info("Server IP: "+ host + " listening on port " + port + ""); 	

		while(status == 0) {
			try {
				logger.info("Waiting for connections.");
				client = ssChannel.accept();
	
				logger.info("Accepted a connection from: "+ client.socket().getInetAddress());
				
				channel = idaemon.getClass().newInstance(); 

				channel.Connect(client.socket());
				} catch(Exception e) {
					logger.info("Error acepting the connection." + e.getMessage());
			}
				
		}	    
	    
	    
    }
    
	/**
	 * Close.
	 *
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
    public void close() throws IOException{
		status = 1;
		//channel.cleanup();
    	//client.close();
    	ssChannel.close() ; 
		logger = null;    	
   	}
    
}
